/**
 * 小红书发布器模块测试
 */

const XiaohongshuElectronPublisher = require('../lib/index');
const path = require('path');
const fs = require('fs');

console.log('🧪 开始测试小红书发布器模块...');

// 测试配置
const testDataDir = path.join(__dirname, 'test-data');

// Mock Electron API
const mockElectron = {
  BrowserWindow: class {
    constructor(options) {
      this.options = options;
      this.id = Date.now();
    }
    loadURL(url) {
      console.log(`📱 模拟加载URL: ${url}`);
      return Promise.resolve();
    }
    on(event, callback) {
      console.log(`🎧 监听事件: ${event}`);
    }
    close() {
      console.log('🔻 模拟关闭窗口');
    }
    webContents = {
      on: (event, callback) => {
        console.log(`🎧 WebContents监听事件: ${event}`);
        if (event === 'did-finish-load') {
          setTimeout(() => callback(), 100);
        }
      },
      executeJavaScript: (script) => {
        console.log('🔧 模拟执行JavaScript脚本');
        return Promise.resolve();
      }
    }
  },
  session: {
    defaultSession: {
      cookies: {
        get: (filter) => {
          console.log('🍪 模拟获取Cookies');
          return Promise.resolve([
            { name: 'test_cookie', value: 'test_value', domain: '.xiaohongshu.com' }
          ]);
        },
        set: (details) => {
          console.log('🍪 模拟设置Cookie:', details.name);
          return Promise.resolve();
        }
      }
    }
  },
  ipcMain: {
    handle: (channel, handler) => {
      console.log(`📡 注册IPC处理器: ${channel}`);
    }
  }
};

// 替换 require('electron')
const Module = require('module');
const originalRequire = Module.prototype.require;
Module.prototype.require = function(id) {
  if (id === 'electron') {
    return mockElectron;
  }
  return originalRequire.apply(this, arguments);
};

// 测试函数
async function runTests() {
  console.log('\n1️⃣ 测试模块实例化...');
  
  try {
    // 创建测试数据目录
    if (!fs.existsSync(testDataDir)) {
      fs.mkdirSync(testDataDir, { recursive: true });
    }
    
    const publisher = new XiaohongshuElectronPublisher({
      mainWindow: null,
      autoInitDB: true,
      autoRegisterIPC: false,
      dataDir: testDataDir
    });
    
    console.log('✅ 模块实例化成功');
    
    console.log('\n2️⃣ 测试数据库初始化...');
    
    let retryCount = 0;
    while (!publisher.isReady() && retryCount < 50) {
      await new Promise(resolve => setTimeout(resolve, 100));
      retryCount++;
    }
    
    if (publisher.isReady()) {
      console.log('✅ 数据库初始化成功');
    } else {
      throw new Error('数据库初始化超时');
    }
    
    console.log('\n3️⃣ 测试账号管理功能...');
    
    const testAccount = {
      account_id: 'test_xiaohongshu_001',
      name: '测试小红书账号',
      platform: 'xiaohongshu',
      cookies: [
        { name: 'sessionid', value: 'test_session', domain: '.xiaohongshu.com' }
      ]
    };
    
    const saveResult = await publisher.saveAccount(testAccount);
    if (saveResult.success) {
      console.log('✅ 账号保存成功');
    } else {
      throw new Error('账号保存失败: ' + saveResult.error);
    }
    
    const getResult = await publisher.getAccountByAccountId('test_xiaohongshu_001');
    if (getResult.success && getResult.data) {
      console.log('✅ 账号查询成功');
    } else {
      throw new Error('账号查询失败');
    }
    
    const allAccountsResult = await publisher.getAccounts();
    if (allAccountsResult.success) {
      console.log(`✅ 获取账号列表成功，共 ${allAccountsResult.data.length} 个账号`);
    } else {
      throw new Error('获取账号列表失败');
    }
    
    console.log('\n4️⃣ 测试发布记录功能...');
    
    const testRecord = {
      account_id: 'test_xiaohongshu_001',
      title: '测试小红书发布内容',
      content: '这是一个测试发布记录',
      content_type: 'image',
      file_url: 'https://example.com/test.jpg',
      tags: '测试,小红书',
      status: 'draft'
    };
    
    const recordResult = await publisher.savePublishRecord(testRecord);
    if (recordResult.success) {
      console.log('✅ 发布记录保存成功');
    } else {
      throw new Error('发布记录保存失败: ' + recordResult.error);
    }
    
    const recordsResult = await publisher.getPublishRecords();
    if (recordsResult.success) {
      console.log(`✅ 获取发布记录成功，共 ${recordsResult.data.length} 条记录`);
    } else {
      throw new Error('获取发布记录失败');
    }
    
    const recordsByAccountResult = await publisher.getPublishRecordsByAccountId('test_xiaohongshu_001');
    if (recordsByAccountResult.success) {
      console.log(`✅ 按账号获取发布记录成功，共 ${recordsByAccountResult.data.length} 条记录`);
    } else {
      throw new Error('按账号获取发布记录失败');
    }
    
    console.log('\n5️⃣ 测试资源清理...');
    
    await publisher.close();
    console.log('✅ 资源清理成功');
    
    console.log('\n🎉 所有测试通过！');
    console.log('==========================================');
    console.log('📊 测试结果汇总:');
    console.log('  ✅ 模块实例化: 通过');
    console.log('  ✅ 数据库初始化: 通过');
    console.log('  ✅ 账号管理: 通过');
    console.log('  ✅ 发布记录: 通过');
    console.log('  ✅ 资源清理: 通过');
    console.log('');
    console.log('🚀 模块已准备就绪，可以集成到您的项目中使用！');
    
  } catch (error) {
    console.error('\n❌ 测试失败:', error.message);
    console.error('详细信息:', error.stack);
    process.exit(1);
  } finally {
    // 清理测试数据
    try {
      if (fs.existsSync(testDataDir)) {
        fs.rmSync(testDataDir, { recursive: true, force: true });
        console.log('🧹 测试数据清理完成');
      }
    } catch (error) {
      console.warn('⚠️ 清理测试数据失败:', error.message);
    }
  }
}

// 运行测试
runTests();
